package com.hivekion.common.config;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.hivekion.common.core.SwaggerProperties;
import com.hivekion.common.security.JwtTokenUtils;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.lang.reflect.Field;
import java.util.*;

@Configuration
@EnableOpenApi
public class SwaggerConfig implements WebMvcConfigurer {
    // 定义分隔符
    private static final String splitor = ";";

    private final SwaggerProperties swaggerProperties;

    public SwaggerConfig(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

    @Bean
    public Docket createFileRestApi() {
        return createRestApi("com.hivekion.files.controller", "文件上传");
    }

    @Bean
    public Docket createEpidemicRestApi() {
        return createRestApi("com.hivekion.epidemic.controller", "疫情防控");
    }

    @Bean
    public Docket createQuartzRestApi() {
        return createRestApi("com.hivekion.quartz.controller", "定时任务");
    }

    @Bean
    public Docket createSummaryRestApi() {
        return createRestApi("com.hivekion.summary.controller", "统计汇总服务");
    }

    @Bean
    public Docket createIntegralRestApi() {
        return createRestApi("com.hivekion.integral.controller", "积分查询服务");
    }

    @Bean
    public Docket createStatistiConfigcalRestApi() {
        return createRestApi("com.hivekion.statisticalconfig.controller", "汇总台账");
    }

    @Bean
    public Docket createStatisticsHomeRestApi() {
        return createRestApi("com.hivekion.statistics.controller", "其他统计");
    }

    @Bean
    public Docket createSystemRestApi() {
        return createRestApi("com.hivekion.system.controller", "系统管理");
    }

    @Bean
    public Docket createStatisticalRestApi() {
        return createRestApi("com.hivekion.statistical.controller", "统计模块");
    }

    @Bean
    public Docket createCustomerRestApi() {
        return createRestApi("com.hivekion.customer.controller", "用户管理");
    }

    private Docket createRestApi(String backPackage, String groupName) {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(basePackage(backPackage))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts()) // 授权信息全局应用
                .groupName(groupName);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("项目管理系统--API说明文档")
                .description("2021.02.23上线版本")
                .version("1.0")
                .build();
    }

    /**
     * 设置授权信息
     */
    private List<SecurityScheme> securitySchemes() {
        ApiKey apiKey = new ApiKey(JwtTokenUtils.AUTHORIZATION, "token", In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }

    /**
     * 授权信息全局应用
     */
    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(
                                Collections.singletonList(
                                        new SecurityReference(
                                                JwtTokenUtils.AUTHORIZATION,
                                                new AuthorizationScope[]{
                                                        new AuthorizationScope("global", "")
                                                })))
                        .build());
    }

    @SafeVarargs
    private final <T> Set<T> newHashSet(T... ts) {
        if (ts.length > 0) {
            return new LinkedHashSet<>(Arrays.asList(ts));
        }
        return null;
    }

    /**
     * 通用拦截器排除swagger设置，所有拦截器都会自动加swagger相关的资源排除信息
     */
    @SuppressWarnings("unchecked")
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        try {
            Field registrationsField =
                    FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
            List<InterceptorRegistration> registrations =
                    (List<InterceptorRegistration>)
                            ReflectionUtils.getField(registrationsField, registry);
            if (registrations != null) {
                for (InterceptorRegistration interceptorRegistration : registrations) {
                    interceptorRegistration
                            .excludePathPatterns("/swagger**/**")
                            .excludePathPatterns("/webjars/**")
                            .excludePathPatterns("/v3/**")
                            .excludePathPatterns("/doc.html");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
